package com.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.web.annotation.CurrentUser;
import com.web.annotation.LoginRequired;
import com.web.dao.NoticeMapper;
import com.web.domain.Response;
import com.web.entity.*;
import com.web.enums.NoticeEnum;
import com.web.service.JobService;
import com.web.service.LoginService;
import com.web.service.NoticeService;
import com.web.service.TechRecruitService;
import com.web.utils.GetLocation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.web.utils.GetLocation.getAdd;


@Slf4j
@RestController
@RequestMapping(value = "/app")
public class JobController extends BaseController{

    @Autowired
    private JobService jobService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private TechRecruitService techRecruitService;

    /**
     * 查询学历
     * @param info
     * @return
     */
    @PostMapping("/job/Education")
    public Response getEducationList(@CurrentUser UserInfo info){
        List<UserEdu> list = jobService.getEducationList();
        return Response.custom().ok().addParams(list);
    }

    /**
     * 发布求职
     * @param info
     * @return
     */
    @RequestMapping("/job/JobWanted")
    public Response JobWanted(@CurrentUser UserInfo info,JobHunting jobHunting){
        int type = getUserCertification(info.getUserId());
        if(type==2){
            return Response.custom().failure("请完善个人资料再发布求职信息！");
        }
        if(jobHunting.getWork_type()==1){
            jobHunting.setContact_info(jobHunting.getContact_info());
            jobHunting.setUser_id(info.getUserId());
            jobHunting.setPost(jobHunting.getPost());
            jobHunting.setWork_type(jobHunting.getWork_type());
            jobHunting.setMin_salary(jobHunting.getMin_salary());
            jobHunting.setMax_salary(jobHunting.getMax_salary());
            jobHunting.setLongitude(jobHunting.getLongitude());
            jobHunting.setLatitude(jobHunting.getLatitude());
            jobHunting.setEdu_id(jobHunting.getEdu_id());
            jobHunting.setContact_info(jobHunting.getContact_info());
            jobHunting.setExperience_work(jobHunting.getExperience_work());
            jobHunting.setJob_hunting_description(jobHunting.getJob_hunting_description());
            jobHunting.setWork_status(jobHunting.getWork_status());
            jobHunting.setModify_time(new Date());
            jobHunting.setCreate_time(new Date());
            jobService.insertjobHunting(jobHunting);
            return Response.custom().ok("发布成功！");
        }
        if(jobHunting.getWork_type()==2){
            jobHunting.setContact_info(jobHunting.getContact_info());
            jobHunting.setUser_id(info.getUserId());
            jobHunting.setPost(jobHunting.getPost());
            jobHunting.setWork_type(jobHunting.getWork_type());
            jobHunting.setMin_salary(jobHunting.getMin_salary());
            jobHunting.setMax_salary(jobHunting.getMax_salary());
            jobHunting.setLongitude(jobHunting.getLongitude());
            jobHunting.setLatitude(jobHunting.getLatitude());
            jobHunting.setEdu_id(jobHunting.getEdu_id());
            jobHunting.setContact_info(jobHunting.getContact_info());
            jobHunting.setExperience_work(jobHunting.getExperience_work());
            jobHunting.setJob_hunting_description(jobHunting.getJob_hunting_description());
            jobHunting.setWork_status(jobHunting.getWork_status());
            jobHunting.setDuration(jobHunting.getDuration());
            jobHunting.setModify_time(new Date());
            jobHunting.setCreate_time(new Date());
            jobService.insertjobHunting(jobHunting);
            return Response.custom().ok("发布成功！");
        }
        return Response.custom().failure("发布失败请联系管理员！");
    }


    /**
     * 企业招聘
     * @param info
     * @return
     */
    @RequestMapping("/job/EnterpriseRecruitment")
    public Response EnterpriseRecruitment(@CurrentUser UserInfo info,TechRecriitment techRecriitment){
        //个人资料是否完善
        int type = getUserCertification(info.getUserId());
        //企业信息是否完善
        int type1 = getTechInfo(info.getUserId());
        if(type == 2 ){
            return Response.custom().failure("请完善个人资料再发布求职信息！");
        }
        if(type1 == 2){
            return Response.custom().failure("请完善企业信息再发布求职信息！");
        }
        if(techRecriitment.getRecruitment_type()==1){
            techRecriitment.setUser_id(info.getUserId());
            techRecriitment.setPost(techRecriitment.getPost());
            techRecriitment.setRecruitment_type(techRecriitment.getRecruitment_type());
            techRecriitment.setWork_year(techRecriitment.getWork_year());
            techRecriitment.setMin_salary(techRecriitment.getMin_salary());
            techRecriitment.setMax_salary(techRecriitment.getMax_salary());
            techRecriitment.setLatitude(techRecriitment.getLatitude());
            techRecriitment.setLongitude(techRecriitment.getLongitude());
            techRecriitment.setEdu_id(techRecriitment.getEdu_id());
            techRecriitment.setContact(techRecriitment.getContact());
            techRecriitment.setContact_information(techRecriitment.getContact_information());
            techRecriitment.setCreate_time(new Date());
            techRecriitment.setModify_time(new Date());
            techRecriitment.setPost_info(techRecriitment.getPost_info());
            jobService.insertEnterpriseRecruitment(techRecriitment);
            return Response.custom().ok();
        }
        else if(techRecriitment.getRecruitment_type()==2){
            techRecriitment.setUser_id(info.getUserId());
            techRecriitment.setPost(techRecriitment.getPost());
            techRecriitment.setRecruitment_type(techRecriitment.getRecruitment_type());
            techRecriitment.setDuration(techRecriitment.getDuration());
            techRecriitment.setWork_year(techRecriitment.getWork_year());
            techRecriitment.setMin_salary(techRecriitment.getMin_salary());
            techRecriitment.setMax_salary(techRecriitment.getMax_salary());
            techRecriitment.setLatitude(techRecriitment.getLatitude());
            techRecriitment.setLongitude(techRecriitment.getLongitude());
            techRecriitment.setEdu_id(techRecriitment.getEdu_id());
            techRecriitment.setContact(techRecriitment.getContact());
            techRecriitment.setContact_information(techRecriitment.getContact_information());
            techRecriitment.setCreate_time(new Date());
            techRecriitment.setModify_time(new Date());
            techRecriitment.setPost_info(techRecriitment.getPost_info());
            jobService.insertEnterpriseRecruitment(techRecriitment);
            return Response.custom().ok();
        }

        return Response.custom().failure("发布失败请联系管理员！");
    }


    /**
     * 招聘详情
     * @param info
     * @return
     */
    @PostMapping("/job/details")
    public Response RecruitmentDetails(@CurrentUser UserInfo info,Integer id){
        if (id == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        RecruitmentDetails recruitmentDetails = jobService.getRecruitmentDetails(id,info.getUserId());
        recruitmentDetails.setCity(GetLocation.getCityName(getAdd(recruitmentDetails.getLongitude(),recruitmentDetails.getLatitude())));
        if(recruitmentDetails==null){
            return Response.custom().failure("没有这条招聘！");
        }
        return Response.custom().ok().addParams(recruitmentDetails);
    }

    /**
     * 应聘
     * @param info
     * @param id
     * @return
     */
    @PostMapping("/job/toEmploy")
    public Response toEmploy(@CurrentUser UserInfo info, Integer id) {
        if (id == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        TechRecruit techRecruit = techRecruitService.getRecruit(id);
        if (techRecruit == null) {
            return Response.custom().failure("未找到该条招聘信息!");
        }
        if (loginService.findUserJob(info.getUserId()) == null) {
            return Response.custom().failure("简历未上传，暂不能应聘!");
        }
        //判断是否已经应聘
        if (noticeService.searchIsRepeatRecruit(info.getUserId(), id) != null) {
            return Response.custom().failure("您已应聘，无需再次应聘!");
        }
        Notice notice = new Notice();
        notice.setType(NoticeEnum.RECRUIT_NOTICE.getCode());
        notice.setSender(info.getUserId());
        notice.setTarget(techRecruit.getUserId());
        notice.setTitle("应聘通知");
        notice.setContent("您发布的"+techRecruit.getPost()+"岗位有人应聘了");
        notice.setContentId(techRecruit.getId());
        Integer flag = noticeService.insert(notice);
        if (flag > 0) {
            return Response.custom().ok();
        } else {
            return Response.custom().failure("应聘失败！");
        }
    }

    /**
     * 聘用
     * @param userInfo
     * @param id
     * @return
     */
    @PostMapping("/job/hire")
    public Response hire(@CurrentUser UserInfo userInfo, Integer id) {
        if (id == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        //判断是否重复聘用
        if (noticeService.searchIsRepeatJobApply(userInfo.getUserId(), id) != null) {
            return Response.custom().failure("您已聘用该用户，无需再次聘用!");
        }
        JobApply jobApply = jobService.getJobById(id);
        if (jobApply == null) {
            return Response.custom().failure("未找到该条求职信息!");
        }
        Notice notice = new Notice();
        notice.setType(NoticeEnum.JOB_NOTICE.getCode());
        notice.setSender(userInfo.getUserId());
        notice.setTitle("聘用通知");
        notice.setContent("您的求职有公司聘用了");
        notice.setTarget(jobApply.getUserId());
        Integer flag = noticeService.insert(notice);
        if (flag > 0) {
            return Response.custom().ok();
        } else {
            return Response.custom().failure("应聘失败！");
        }
    }

    /**
     * 求职详情
     * @param info
     * @return
     */
    @PostMapping("/job/JobWantedDetails")
    public Response JobWantedDetails(@CurrentUser UserInfo info,Integer id,String userId){
        if (id == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        Map<String,Object> map = new HashMap<>();
        TemporaryWorkDetails temporaryWorkDetails = jobService.getJobWantedDetails(id,info.getUserId());
        if(temporaryWorkDetails==null){
            return Response.custom().failure("没有这条求职！");
        }

        temporaryWorkDetails.setCity(GetLocation.getCityName(getAdd(temporaryWorkDetails.getLongitude(),temporaryWorkDetails.getLatitude())));
        map.put("temporaryWorkDetails",temporaryWorkDetails);
        map.put("Experience",loginService.myExperience(userId));
        map.put("Case",loginService.myCase(userId));
        System.out.println("map : " + map);
        return Response.custom().ok().addParams(map);
    }

    /**
     * 临工求职详情
     * @param info
     * @param id
     * @return
     */
    @PostMapping("/job/TemporaryWorkDetails")
    public Response TemporaryWorkDetails(@CurrentUser UserInfo info,Integer id,String userId){
        if (id == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        Map<String,Object> map = new HashMap<>();
        TemporaryWorkDetails temporaryWorkDetails = jobService.getTemporaryWorkDetails(id,info.getUserId());
        if(temporaryWorkDetails==null){
            return Response.custom().failure("没有这条求职！");
        }
        temporaryWorkDetails.setCity(GetLocation.getCityName(getAdd(temporaryWorkDetails.getLongitude(),temporaryWorkDetails.getLatitude())));
        map.put("temporaryWorkDetails",temporaryWorkDetails);
        map.put("Experience",loginService.myExperience(userId));
        map.put("Case",loginService.myCase(userId));
        System.out.println("map : " + map);
        return Response.custom().ok().addParams(map);

    }

   

    /**
     * 企业招聘，求职，临时工列表
     * @return
     */
    @LoginRequired
    @PostMapping("/job/JobList")
    public Response JobList(Integer pageNum,String city, String min_salary, String max_salary,
                            Integer type) throws IOException {
            if (pageNum == null){
                return Response.custom().failure("缺少请求参数pageNum,请重新核对后再提交!");
            }
            if(type == null){
                return Response.custom().failure("缺少请求参数type,请重新核对后再提交!");
            }
            //企业
            if(type == 1){
                if(StringUtils.isBlank(city)){
                    PageHelper.startPage(pageNum,10);
                    List<JobList> commentReplyLists = jobService.getEnterpriseRecruitment(min_salary,max_salary);
                    for(int i =0;i<commentReplyLists.size();i++){
                        String Longitude = commentReplyLists.get(i).getLongitude();
                        String Latitude = commentReplyLists.get(i).getLatitude();
                        commentReplyLists.get(i).setCity(GetLocation.getCityName(getAdd(Longitude,Latitude)));
                    }
                    PageInfo pageInfo = new PageInfo(commentReplyLists,10);
                    if(pageNum > pageInfo.getPages()){
                        return Response.custom().ok().addParams(new List[0]);
                    }else{
                        return Response.custom().ok().addParams(pageInfo.getList());
                    }
                }else {
                    String[] coordinate =GetLocation.getCoordinate(city);
                    String longitude = coordinate[0];//经度
                    String latitude = coordinate[1];//纬度
                    if (pageNum == null){
                        return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
                    }

                    PageHelper.startPage(pageNum,10);
                    List<JobList> commentReplyLists = jobService.getEnterpriseRecruitmentList(min_salary,max_salary,longitude,latitude);
                    for(int i =0;i<commentReplyLists.size();i++){
                        commentReplyLists.get(i).setCity(GetLocation.getCityName(getAdd(commentReplyLists.get(i).getLongitude(),commentReplyLists.get(i).getLatitude())));
                    }
                    PageInfo pageInfo = new PageInfo(commentReplyLists,10);
                    if(pageNum > pageInfo.getPages()){
                        return Response.custom().ok().addParams(new List[0]);
                    }else{
                        return Response.custom().ok().addParams(pageInfo.getList());
                    }
                }

            }else if(type ==2){
                //求职
                if(StringUtils.isBlank(city)){
                    PageHelper.startPage(pageNum,10);
                    List<JobList> commentReplyLists = jobService.getJobListtwo(min_salary,max_salary);
                    for(int i =0;i<commentReplyLists.size();i++){
                        commentReplyLists.get(i).setCity(GetLocation.getCityName(getAdd(commentReplyLists.get(i).getLongitude(),commentReplyLists.get(i).getLatitude())));
                    }
                    PageInfo pageInfo = new PageInfo(commentReplyLists,10);
                    if(pageNum > pageInfo.getPages()){
                        return Response.custom().ok().addParams(new List[0]);
                    }else{
                        return Response.custom().ok().addParams(pageInfo.getList());
                    }
                }else {
                    String[] coordinate =GetLocation.getCoordinate(city);
                    String longitude = coordinate[0];//经度
                    String latitude = coordinate[1];//纬度
                    if (pageNum == null){
                        return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
                    }

                    PageHelper.startPage(pageNum,10);
                    List<JobList> commentReplyLists = jobService.getJobList(longitude,latitude,min_salary,max_salary);
                    for(int i =0;i<commentReplyLists.size();i++){
                        commentReplyLists.get(i).setCity(GetLocation.getCityName(getAdd(commentReplyLists.get(i).getLongitude(),commentReplyLists.get(i).getLatitude())));
                    }
                    PageInfo pageInfo = new PageInfo(commentReplyLists,10);
                    if(pageNum > pageInfo.getPages()){
                        return Response.custom().ok().addParams(new List[0]);
                    }else{
                        return Response.custom().ok().addParams(pageInfo.getList());
                    }
                }
            }else if(type ==3){
                //临时工
                if(StringUtils.isBlank(city)){

                    PageHelper.startPage(pageNum,10);
                    List<JobList> commentReplyLists = jobService.getTemporaryWorkers(min_salary,max_salary);
                    for(int i =0;i<commentReplyLists.size();i++){
                        commentReplyLists.get(i).setCity(GetLocation.getCityName(getAdd(commentReplyLists.get(i).getLongitude(),commentReplyLists.get(i).getLatitude())));
                    }
                    PageInfo pageInfo = new PageInfo(commentReplyLists,10);
                    if(pageNum > pageInfo.getPages()){
                        return Response.custom().ok().addParams(new List[0]);
                    }else{
                        return Response.custom().ok().addParams(pageInfo.getList());
                    }
                }else {
                    String[] coordinate =GetLocation.getCoordinate(city);
                    String longitude = coordinate[0];//经度
                    String latitude = coordinate[1];//纬度
                    if (pageNum == null){
                        return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
                    }

                    PageHelper.startPage(pageNum,10);
                    List<JobList> commentReplyLists = jobService.TemporaryWorkersList(longitude,latitude,min_salary,max_salary);
                    for(int i =0;i<commentReplyLists.size();i++){
                        commentReplyLists.get(i).setCity(GetLocation.getCityName(getAdd(commentReplyLists.get(i).getLongitude(),commentReplyLists.get(i).getLatitude())));
                    }
                    PageInfo pageInfo = new PageInfo(commentReplyLists,10);
                    if(pageNum > pageInfo.getPages()){
                        return Response.custom().ok().addParams(new List[0]);
                    }else{
                        return Response.custom().ok().addParams(pageInfo.getList());
                    }
                }
            }
            return Response.custom().failure("系统异常请联系管理员！");
    }


}
